﻿using Model;
using System;
using System.Collections.Generic;

namespace Hotfix
{
    /// <summary>
    /// 操作码类型工具
    /// </summary>
    public class OpcodeTypeHelper : Singleton<OpcodeTypeHelper>
    {
        /// <summary>
        /// 初始化开始
        /// </summary>
        public void StartInit()
        {
            Type[] types = this.GetType().Assembly.GetTypes();
            foreach (var item in types)
            {
                object[] obj = item.GetCustomAttributes(typeof(MessagerAttribute), false);
                if (obj.Length == 0) continue;

                MessagerAttribute messager = obj[0] as MessagerAttribute;
                dicOpcodeType[messager.opcode] = item;
                dicMassgerAttribute[item] = messager;
            }
        }

        /// <summary>
        /// 将标记,特性类型的类 放入字典集合中(这个特性就是需要转换类的类型 比如:服务器响应过来,
        /// 登录成功就需要拿:Login类来接收 . 实现查看:Outermessage.cs)
        /// </summary>
        Dictionary<Opcode, Type> dicOpcodeType = new Dictionary<Opcode, Type>();

        /// <summary>
        /// 将反射出来的类和特性放入字典集合中,方便查找类型
        /// </summary>
        Dictionary<Type, MessagerAttribute> dicMassgerAttribute = new Dictionary<Type, MessagerAttribute>();


        /// <summary>
        /// 返回消息类型
        /// </summary>
        /// <param name="opcode"></param>
        /// <returns></returns>
        public Type GetOpcodeToType(Opcode opcode)
        {
            if (!dicOpcodeType.TryGetValue(opcode, out Type type))
            {
                throw new Exception($"查找Type失败:{opcode}");
            }
            return type;
        }

        /// <summary>
        /// 返回消息对应的类
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public MessagerAttribute GetTypeTomessager(Type type)
        {
            if (!dicMassgerAttribute.TryGetValue(type, out MessagerAttribute messager))
            {
                throw new Exception($"查找Opcode失败: {type.Name}");
            }

            return messager;
        }


    }
}
